package com.baseframe.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.baseframe.common.annotation.SysLog;
import com.baseframe.common.exception.RRException;
import com.baseframe.common.utils.Constant;
import com.baseframe.common.utils.R;
import com.baseframe.sys.entity.FrameOnlineMessage;
import com.baseframe.sys.entity.FrameModule;
import com.baseframe.sys.entity.FrameModulePrivilege;
import com.baseframe.sys.entity.FrameRole;
import com.baseframe.sys.service.IFrameOnlineMessageService;
import com.baseframe.sys.service.IFrameModuleService;
import com.baseframe.sys.service.IFrameRoleService;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统菜单
 *
 * @author chenjia ghoulbfo@gmail.com
 * @date 2016年10月27日 下午9:58:15
 */
@RestController
@RequestMapping("/sys/menu")
public class FrameModuleController extends AbstractController {

    @Autowired
    private IFrameModuleService frameModuleService;

    @Autowired
    private IFrameRoleService frameRoleService;
    @Autowired
	private IFrameOnlineMessageService messageService;

    /**I
     * 导航菜单
     */
    @RequestMapping("/nav")
    public R nav() {
        List<FrameModule> menuList = frameModuleService.getUserMenuList(getUserguid());
        return R.ok().put("menuList", menuList);
    }
    
    /**
     * 所有菜单列表
     */
    @RequestMapping("/list")
    public List<FrameModule> list() {
        List<FrameModule> menuList = frameModuleService.selectList();

        menuList.forEach(sysMenu -> {
            Optional<FrameModule> parentMenuOptional = menuList.stream()
                    .filter(tempMenu -> tempMenu.getModuleguid().equals(sysMenu.getParentguid()))
                    .findFirst();
            if (parentMenuOptional.isPresent()) {
                sysMenu.setParentName(parentMenuOptional.get().getModulename());
            } else {
                sysMenu.setParentName("根");
            }
        });
        return menuList;
    }

    /**
     * 选择菜单(添加、修改菜单)
     */
    @RequestMapping("/select")
    public R select() {
        //查询列表数据
        List<FrameModule> menuList = frameModuleService.queryNotButtonList();

        //添加顶级菜单
        FrameModule root = new FrameModule();
        root.setModuleguid("0");
        root.setModulename("一级菜单");
        root.setParentguid("root");
        root.setOpen(true);
        menuList.add(root);

        return R.ok().put("menuList", menuList);
    }

    /**
     * 菜单信息
     */
    @RequestMapping("/info/{menuId}")
    public R info(@PathVariable("menuId") String menuId) {
        FrameModule menu = frameModuleService.selectById(menuId);
        return R.ok().put("menu", menu);
    }

    /**
     * 保存
     */
    @SysLog(value="保存菜单", type="新增")
    @RequestMapping("/save")
    public R save(@RequestBody FrameModule menu) {
        //数据校验
        verifyForm(menu);
        menu.setModuleguid(UUID.randomUUID().toString());
        frameModuleService.insert(menu);

        return R.ok();
    }

    /**
     * 修改
     */
    @SysLog(value="修改菜单", type="修改")
    @RequestMapping("/update")
    public R update(@RequestBody FrameModule menu) {
        //数据校验
        verifyForm(menu);

        frameModuleService.update(menu);

        return R.ok();
    }

    /**
     * 删除
     */
    @SysLog(value="删除菜单", type="删除")
    @RequestMapping("/delete")
    public R delete(String menuId) {
        /* TODO 这里需要处理下系统菜单不可删除
        if (menuId <= 31) {
            return R.error("系统菜单，不能删除");
        }*/

        //判断是否有子菜单或按钮
        List<FrameModule> menuList = frameModuleService.queryListParentId(menuId);
        if (menuList.size() > 0) {
            return R.error("请先删除子菜单或按钮");
        }

        frameModuleService.delete(menuId);

        return R.ok();
    }

    /**
     * 验证参数是否正确
     */
    private void verifyForm(FrameModule frameModule) {
        if (StringUtils.isBlank(frameModule.getModulename())) {
            throw new RRException("菜单名称不能为空");
        }

        if (frameModule.getParentguid() == null) {
            throw new RRException("上级菜单不能为空");
        }

        //菜单
        if (frameModule.getModuletype() == Constant.MenuType.MENU.getValue()) {
            if (StringUtils.isBlank(frameModule.getModuleurl())) {
                throw new RRException("菜单URL不能为空");
            }
        }

        //上级菜单类型
        int parentType = Constant.MenuType.CATALOG.getValue();
        if (!"0".equals(frameModule.getParentguid())) {
            FrameModule parentMenu = frameModuleService.selectById(frameModule.getParentguid());
            parentType = parentMenu.getModuletype();
        }

        //目录、菜单
        if (frameModule.getModuletype() == Constant.MenuType.CATALOG.getValue() ||
                frameModule.getModuletype() == Constant.MenuType.MENU.getValue()) {
            if (parentType != Constant.MenuType.CATALOG.getValue()) {
                throw new RRException("上级菜单只能为目录类型");
            }
            return;
        }

        //按钮
        if (frameModule.getModuletype() == Constant.MenuType.BUTTON.getValue()) {
            if (parentType != Constant.MenuType.MENU.getValue()) {
                throw new RRException("上级菜单只能为菜单类型");
            }
            return;
        }
    }

    @SysLog("设置菜单权限")
    @RequestMapping("/moduleRoleList/{menuId}")
    public R moduleRoleList(@PathVariable("menuId") String moduleGuid) {
        List<FrameRole> frameRoleList = frameRoleService.findAll();
        List<FrameModulePrivilege> frameModulePrivilegeList = frameModuleService.findByAllowtype("Role");

        List<String> optional = frameModulePrivilegeList.stream().
                filter(frameModulePrivilege -> frameModulePrivilege.getModuleguid().equals(moduleGuid))
                .map(frameModulePrivilege -> frameModulePrivilege.getAllowto())
                .collect(Collectors.toList());
        Map<String, Object> roleMap = new HashMap<>(1);
        roleMap.put("roleList", frameRoleList);
        roleMap.put("roleIds", optional);
        return R.ok().put("roleMap", roleMap);
    }

    @RequestMapping("saveModuleRight")
    @Transactional
    public R saveModuleRight(@RequestBody JSONObject moduleRight) {
        List<String> roleIds = moduleRight.getJSONArray("roleIds").toJavaList(String.class);
        String moduleGuid = moduleRight.getString("moduleGuid");

        frameModuleService.deleteByModuleguidAndAllowtype(moduleGuid, "Role");

        roleIds.forEach(roleGuid -> {
            FrameModulePrivilege frameModulePrivilege = new FrameModulePrivilege();
            frameModulePrivilege.setRowguid(UUID.randomUUID().toString());
            frameModulePrivilege.setModuleguid(moduleGuid);
            frameModulePrivilege.setAllowto(roleGuid);
            frameModulePrivilege.setAllowtype("Role");

            frameModulePrivilege.setCreateTime(new Date());

            frameModuleService.save(frameModulePrivilege);
        });
        return R.ok();
    }
}
